package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {

    // 依赖
    @Autowired
    private DishMapper dishMapper; // 菜品

    @Autowired
    private DishFlavorMapper dishFlavorMapper; // 菜品口味

    @Autowired
    private CategoryMapper categoryMapper; // 分类

    //分页查询+条件查询
    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {
        //1. 构建菜品条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(name), Dish::getName, name);
        //2.开启分页
        Page<Dish> page = new Page<>(pageNum, pageSize);
        //3.分页查询
        page = dishMapper.selectPage(page, qw);
        //4.遍历菜品列表
        List<Dish> dishList = page.getRecords();
        for (Dish dish : dishList) {
            // 4.1 根据菜品id查询口味列表
            // 4.1.1 构建条件
            LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
            dqw.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(dqw);
            //封装口味列表
            dish.setFlavors(dishFlavorList);

            //根据分类分id查询类列表
            Category category = categoryMapper.selectById(dish.getCategoryId());
            //封装分类名称
            dish.setCategoryName(category.getName());
        }
        return page;
    }

    //新增菜品
    @Override
    public void save(Dish dish) {
        // 1. 新增菜品信息
        log.info("新增之前:" + dish.getId());
        dishMapper.insert(dish);
        log.info("新增之后:" + dish.getId());

        // 2.遍历口味
        for (DishFlavor flavor : dish.getFlavors()) {
            //关联菜品
            flavor.setDishId(dish.getId());
            //新增口味
            dishFlavorMapper.insert(flavor);
        }
        //新增菜品时选择的分类id
        redisTemplate.delete("dish:"+dish.getCategoryId());
    }

    //回显菜品
    @Override
    public Dish findById(Long id) {
        // 1.先查菜品
        Dish dish = dishMapper.selectById(id);
        // 2.根据菜品id查询口味
        // 2.1 构建条件
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        // 2.2 调用mapper
        List<DishFlavor> dishFlavorList = dishFlavorMapper.selectList(qw);
        // 3.将口味设置到菜品
        dish.setFlavors(dishFlavorList);
        return dish;
    }

    // 修改菜品
    @Override
    public void updateById(Dish dish) {
        // 1. 修改菜品信息
        dishMapper.updateById(dish);
        // 根据菜品id删除原来的口味
        // 构建条件
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dish.getId());
        dishFlavorMapper.delete(qw);
        // 遍历新增口味
        for (DishFlavor flavor : dish.getFlavors()) {
            //关联菜品id
            flavor.setDishId(dish.getId());
            // 口味新增
            dishFlavorMapper.insert(flavor);
        }
        //清除dish所有缓存
        //1.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        //2.批量删除
        redisTemplate.delete(dishKeys);
    }

    //分类查询菜品
    @Override
    public List<Dish> findListByCategoryId(Long categoryId, String name) {
        // 1.构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotBlank(name), Dish::getName, name);
        qw.eq(categoryId != null, Dish::getCategoryId, categoryId); // 根据分类查询
        qw.eq(Dish::getStatus, 1); // 起售状态
        return dishMapper.selectList(qw);

    }


    //删除菜品
    @Override
    public void deleteBatchIds(List<Long> ids) {
        //1.判断是否在起售状态
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids); // 数组
        qw.eq(Dish::getStatus, 1); //判断状态
        Integer integer = dishMapper.selectCount(qw);
        if (integer > 0) {
            throw new CustomException("菜品正在热卖,如果想删除,请先停售再删除");
        }
        //删除菜品
        dishMapper.deleteBatchIds(ids);
        //删除菜品口味
        LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
        dqw.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(dqw);

        //清除dish所有缓存
        //1.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        //2.批量删除
        redisTemplate.delete(dishKeys);
    }

    //停售菜品
    @Override
    public void updateStatus(Integer status, List<Long> ids) {
        //构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);
        //修改实体
        Dish dish = new Dish();
        dish.setStatus(status);
        //调用mapper
        dishMapper.update(dish, qw);

        //清除dish所有缓存
        //1.模糊查询所有key
        Set dishKeys = redisTemplate.keys("dish:*");
        //2.批量删除
        redisTemplate.delete(dishKeys);
    }

    @Autowired
    private RedisTemplate redisTemplate;

    //菜品展示
    @Override
    public List<Dish> findList(Long categoryId, Integer status) {
        //声明返回list
        List<Dish> dishList = null;

        //定义菜品分类的key
        String dishKey = "dish:" + categoryId;

        //先查询redis是否有1
        if (redisTemplate.hasKey(dishKey)) {
            log.info("查询redis");
            //如果有,指直接返回
            dishList= (List<Dish>) redisTemplate.opsForValue().get(dishKey);
        } else {
            log.info("查询MySQL");
            //如果没有查询MySQL
            // 1.查询该分类下起售的菜品有哪些
            // 1.1 构建条件
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(Dish::getCategoryId, categoryId);
            qw.eq(Dish::getStatus, status);
            // 1.2 调用mapper查询
             dishList = dishMapper.selectList(qw);
            // 2.遍历菜品表
            for (Dish dish : dishList) {
                // 3查询口味列表并封装到菜品中
                LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
                dqw.eq(DishFlavor::getDishId, dish.getId());
                //调用mapper查询
                List<DishFlavor> dishFlavorsList = dishFlavorMapper.selectList(dqw);
                // 添加到菜品中
                dish.setFlavors(dishFlavorsList);
            }
            //同步到redis
            redisTemplate.opsForValue().set(dishKey,dishList);
        }

        //返回结果
        return dishList;
    }


}
